package com.crm.service.utils;

import org.apache.log4j.Logger;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密
 * @author <a href="mailto:huang0510@hotmail.com">HuangHuang</a>
 * @version 1.0
 */
public class MsgDigest {

    private static final Logger LOGGER = Logger.getLogger(MsgDigest.class);

    public static String toHex(byte hash[]) {
        StringBuffer buf = new StringBuffer(hash.length * 2);
        for (byte aHash : hash) {
            if (((int) aHash & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString((int) aHash & 0xff, 16));
        }

        return buf.toString();
    }

    public static String getSHA(String toDigest) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(toDigest.getBytes());
            byte[] b = messageDigest.digest();
            return toHex(b);
        }
        catch (NoSuchAlgorithmException ex) {
            String message = "没有找到 MD5 算法。";
            LOGGER.error(message, ex);
            throw new RuntimeException(message, ex);
        }
    }


}
